import { Button, Card, Divider, Form, Icon, Input, Radio, Select, Spin, message, InputNumber } from "antd";
import React from "react";
import styles from "./index.less"
import { languageModelInfo, languageModelTest, languageModelTestMore, languageModelUpdate } from "@/services/languageModel";
import ReactJson from "react-json-view";
import testStreamFunc from "./testStreamFunc";
import UserSession from "@/UserSession";
import { formatMessage } from 'umi-plugin-react/locale';

class EditLanguageModel extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      spinning: false,
      info: {},
      result: "",
      testLoading: false,
      isFinished: true
    }
  }

  componentDidMount() {
    this.getInfo()
  }

  getInfo = () => {
    this.setState({ spinning: true }, async () => {
      const { match: { params }, form: { setFieldsValue } } = this.props;
      const res = await languageModelInfo({ id: params.id });
      res.apiKey = formatMessage({ id: 'editLanguageModel.defaultEncryptedToken' });
      setFieldsValue(res)
      this.setState({ spinning: false, info: res, status: res.status }, () => {
        if (res.type == 3) {
          res.secretKey = formatMessage({ id: 'editLanguageModel.defaultEncryptedToken' });
          setFieldsValue({ secretKey: res.secretKey });
        };
        // if (res.dateType != 0) {
        //   setTimeout(() => {
        //     setFieldsValue({ replyLimitTimes: res.replyLimitTimes });
        //   }, 200)
        // }
      })
    })
  }

  toBack = () => {
    const { history } = this.props;
    const currentUser = UserSession.getCurrentUser()
    history.push({
      pathname:currentUser.tenantId != '1' ? "/languageModel" : "/llmCenter/languageModel",
      params: {},
    });
  }

  doValidate = (flag) => {
    const { match: { params }, form: { validateFields } } = this.props;
    const that = this;
    validateFields((error, values) => {
      if (!error) {
        if (flag === 'test') {
          that.doTest(values)
        };
        if (flag === "save") {
          that.doSave(values)
        }
      }
    })
  }

  doTest = async values => {
    const { match: { params } } = this.props;
    const { info } = this.state;
    console.log(values);
    if (!values.question) {
      message.error(formatMessage({ id: 'editLanguageModel.required.testContent' }));
      return false;
    };
    let obj = {
      id: params.id,
      modelName: values.modelName,
      api: values.api,
      question: values.question,
      topP: values.topP,
      temperature: values.temperature,
      tokens: values.tokens,
    };
    if (values.apiKey != "默认加密token") {
      obj.apiKey = values.apiKey;
    };
    if (info.type == 3) {
      if (values.secretKey != "默认加密token") {
        obj.secretKey = values.secretKey;
      }
    };
    this.setState({ result: '', testLoading: true, isFinished: false }, () => {
      this.getStreamimg(obj)
    })
  }

  getStreamimg = (obj) => {
    //获取流式测试数据
    testStreamFunc.streamingFunc(obj, (res) => {
      console.log(res);
      let { result } = this.state;
      //type= 1 请求中
      if (res.type == 1) {
        //成功
        if (res.success) {
          result += res.content;
          this.setState({ result, status: 2, testLoading: false, isFinished: false });
        } else {
          //失败
          this.setState({ status: 1, testLoading: false, result: res.content, isFinished: true });
        }
      } else {
        //请求结束
        this.setState({ testLoading: false, isFinished: true });
      }
    })
  }

  doSave = async values => {
    const { info } = this.state;
    const { match: { params } } = this.props;
    let obj = {
      id: params.id,
      modelName: values.modelName,
      api: values.api,
      name: values.name,
      type: info.type,
      topP: values.topP,
      temperature: values.temperature,
      tokens: values.tokens,
      comment: values.comment,
      modelType: values.modelType,
      // dateType: values.dateType,
      // replyLimitTimes: values.replyLimitTimes
    };
    if (values.apiKey != "默认加密token") {
      obj.apiKey = values.apiKey
    };
    if (info.type == 3) {
      if (values.secretKey != "默认加密token") {
        obj.secretKey = values.secretKey
      }
    };
    const res = await languageModelUpdate(obj);
    message.info(res.message);
    this.toBack();
  }

  render() {
    const { form: { getFieldDecorator, getFieldValue }, location: { query: { isSys } } } = this.props;
    const { spinning, info, result, status, testLoading, isFinished } = this.state;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 19 },
      },
    };

    return (
      <Card bordered={false} bodyStyle={{ padding: 0 }}>
        <div className={styles.pageTop}>
          <div className={styles.title}>{formatMessage({ id: 'page.title.modelDetails' })}</div>
          <Button icon="arrow-left" onClick={this.toBack}>{formatMessage({ id: 'button.back' })}</Button>
        </div>
        <Divider style={{ margin: 0 }} />
        <Spin spinning={spinning}>
          <div style={{ padding: 24 }}>
            <Form {...formItemLayout} className="languageForm">
              <div>
                <Form.Item label={formatMessage({ id: 'editLanguageModel.modelName' })} extra={formatMessage({ id: 'editLanguageModel.modelNameDesc' })}>
                  {getFieldDecorator("name", { rules: [{ required: true, message: formatMessage({ id: 'editLanguageModel.required.modelName' }) }] })(
                    <Input placeholder={formatMessage({ id: 'editLanguageModel.placeholder.enterModelName' })} style={{ width: 700 }} />
                  )}
                </Form.Item>
                <Form.Item label={formatMessage({ id: 'editLanguageModel.modelType' })} extra={formatMessage({ id: 'editLanguageModel.modelTypeDesc' })}>
                  {getFieldDecorator("modelType", { initialValue: '1', rules: [{ required: true, message: "请选择模型类型" }] })(
                    <Radio.Group>
                      <Radio value={'1'}>{formatMessage({ id: 'editLanguageModel.internalModel' })}</Radio>
                      <Radio value={'2'}>{formatMessage({ id: 'editLanguageModel.externalModel' })}</Radio>
                    </Radio.Group>
                  )}
                </Form.Item>
                <Form.Item label={formatMessage({ id: 'editLanguageModel.modelId' })}>
                  {getFieldDecorator("modelName", { rules: [{ required: true, message: formatMessage({ id: 'editLanguageModel.required.modelId' }) }] })(
                    <Input placeholder={formatMessage({ id: 'editLanguageModel.placeholder.enterModelId' })} disabled={info.type != 6} style={{ width: 700 }} />
                  )}
                </Form.Item>
                <Form.Item label={formatMessage({ id: 'editLanguageModel.apiUrl' })}>
                  {getFieldDecorator("api", { rules: [{ required: true, message: formatMessage({ id: 'editLanguageModel.required.apiUrl' }) }] })(
                    <Input placeholder={formatMessage({ id: 'editLanguageModel.placeholder.enterApiUrl' })} disabled={info.type != 6} style={{ width: 700 }} />
                  )}
                </Form.Item>
                <Form.Item label={formatMessage({ id: 'editLanguageModel.apiKey' })} extra={formatMessage({ id: 'editLanguageModel.apiKeyDesc' })}>
                  {getFieldDecorator("apiKey", { rules: [{ required: true, message: formatMessage({ id: 'editLanguageModel.required.apiKey' }) }] })(
                    <Input.Password placeholder={formatMessage({ id: 'editLanguageModel.placeholder.enterApiKey' })} visibilityToggle={false} style={{ width: 700 }} disabled={info.type == 0 || info.type == 1} />
                  )}
                </Form.Item>
                {info.type == 3 ? (
                  <Form.Item label={formatMessage({ id: 'editLanguageModel.secretKey' })}>
                    {getFieldDecorator("secretKey", { rules: [{ required: true, message: formatMessage({ id: 'editLanguageModel.required.secretKey' }) }] })(
                      <Input.Password placeholder={formatMessage({ id: 'editLanguageModel.placeholder.enterSecretKey' })} visibilityToggle={false} style={{ width: 700 }} disabled={info.type == 0 || info.type == 1} />
                    )}
                  </Form.Item>
                ) : null}
                <Form.Item label={formatMessage({ id: 'editLanguageModel.topP' })} extra={formatMessage({ id: 'editLanguageModel.topPDesc' })}>
                  {getFieldDecorator("topP", { initialValue: 1.0 })(<Input style={{ width: 700 }} />)}
                </Form.Item>
                <Form.Item label={formatMessage({ id: 'editLanguageModel.temperature' })} extra={formatMessage({ id: 'editLanguageModel.temperatureDesc' })}>
                  {getFieldDecorator("temperature", { initialValue: 0.7 })(<Input style={{ width: 700 }} />)}
                </Form.Item>
                <Form.Item label={formatMessage({ id: 'editLanguageModel.tokens' })} extra={formatMessage({ id: 'editLanguageModel.tokensDesc' })}>
                  {getFieldDecorator("tokens", { initialValue: 4096 })(<Input style={{ width: 700 }} />)}
                </Form.Item>
                <Form.Item label={formatMessage({ id: 'editLanguageModel.description' })}>
                  {getFieldDecorator("comment")(<Input.TextArea autoSize rows={3} style={{ width: 700 }} />)}
                </Form.Item>
              </div>
              <Divider />
              <div>
                <Form.Item label={formatMessage({ id: 'test.title' })}>
                  {getFieldDecorator("question")(<Input placeholder={formatMessage({ id: 'editLanguageModel.placeholder.enterTestContent' })} style={{ width: 400, marginRight: 10 }} />)}
                  <Button type="primary" onClick={() => this.doValidate("test")} disabled={!isFinished}>{formatMessage({ id: 'button.test' })}</Button>
                </Form.Item>
                {result ? (
                  <Form.Item label={formatMessage({ id: 'test.requestResult' })}>
                    <div className={styles.result}>
                      <div dangerouslySetInnerHTML={{ __html: result }}></div>
                    </div>
                  </Form.Item>
                ) : null}
                {testLoading ? (
                  <Form.Item label={formatMessage({ id: 'test.requestResult' })}>
                    <Spin spinning={testLoading}></Spin>
                  </Form.Item>
                ) : null}
                <Form.Item label={formatMessage({ id: 'test.resultStatus' })}>
                  {status == 1 ? (
                    <div className={styles.statusBox} style={{ background: "#FEF1F1", border: "1px solid #FDE2E2" }}>
                      <Icon type="check-circle" theme="filled" style={{ color: "#F54A45" }} />
                      <span style={{ color: '#F54A45' }}>{formatMessage({ id: 'test.status.failed' })}</span>
                    </div>
                  ) : status == 2 ? (
                    <div className={styles.statusBox} style={{ background: "#F1FFF0", border: "1px solid #DAF1D8" }}>
                      <Icon type="check-circle" theme="filled" style={{ color: "#65B85D" }} />
                      <span style={{ color: '#65B85D' }}>{formatMessage({ id: 'test.status.passed' })}</span>
                    </div>
                  ) : formatMessage({ id: 'test.status.untested' })}
                </Form.Item>
              </div>
              {isSys ? null : (
                <>
                  <Divider />
                  <div>
                    <Form.Item label=" " colon={false}>
                      <Button type="primary" style={{ marginRight: 10 }} onClick={() => this.doValidate("save")}>{formatMessage({ id: 'button.save' })}</Button>
                      <Button onClick={this.toBack}>{formatMessage({ id: 'button.cancel' })}</Button>
                    </Form.Item>
                  </div>
                </>
              )}
            </Form>
          </div>
        </Spin>
      </Card>
    )
  }
}

export default Form.create()(EditLanguageModel)